﻿using System;
using Newtonsoft.Json;
using RestSharp;
using WJ.Infrastructure.Serializer;

namespace WJ.Infrastructure.WeChat
{
    public class Account
    {
        RestClient restClient = new RestClient("https://api.weixin.qq.com/");

        public LoginResult Login(string code, LoginType loginType)
        {
            LoginResult loginResult = new LoginResult();

            var appConfig = Config.GetAppConfig(loginType);

            string getAccessTokenUrl = "sns/oauth2/access_token?appid=" + appConfig.AppId + "&secret=" +
                                       appConfig.AppSecret + "&code=" +
                                       code + "&grant_type=authorization_code";

            string getAccessTokenResponse = restClient
                .Execute(new RestRequest(getAccessTokenUrl
                ))
                .Content;


            GetAccessTokenResult getAccessTokenResult =
                JsonConvert.DeserializeObject<GetAccessTokenResult>(getAccessTokenResponse);

//            loginResult.Success = string.IsNullOrEmpty(getAccessTokenResult.errcode)
//                                  && string.IsNullOrEmpty(getAccessTokenResult.errmsg);

            loginResult.Success = !string.IsNullOrEmpty(getAccessTokenResult.openid) &&
                                  !string.IsNullOrEmpty(getAccessTokenResult.unionid);

            loginResult.Error = getAccessTokenResult.errmsg;
            loginResult.OpenId = getAccessTokenResult.openid;
            loginResult.Unionid = getAccessTokenResult.unionid;


            if (loginType == LoginType.MWEB)
            {
                if (loginResult.Success)
                {
                    string getUserInfoResponse = restClient
                        .Execute(new RestRequest("sns/userinfo?access_token=" + getAccessTokenResult.access_token +
                                                 "&openid=" + loginResult.OpenId + "")).Content;


                    WxUserInfo wxUserInfo = JsonConvert.DeserializeObject<WxUserInfo>(getUserInfoResponse);

                    if (string.IsNullOrEmpty(wxUserInfo.errmsg) && string.IsNullOrEmpty(wxUserInfo.errcode))
                    {
                        loginResult.UserInfo = wxUserInfo;
                    }
                    else
                    {
                        loginResult.UserInfo = null;
                    }
                }
            }

            if (!loginResult.Success)
            {
                Log.Log.Info("[微信登陆失败]\r\n请求参数：" + getAccessTokenUrl + "\r\n返回参数：" + getAccessTokenResult.ToJson());
            }

            return loginResult;
        }
    }
}